using System;
using Autofac;
using BanZuiCloudControlAgent.Automation;
using BanZuiCloudControlAgent.Core.Mqtt;
using BanZuiCloudControlAgent.Core.Mqtt.Listener;
using BanZuiCloudControlAgent.Core.Mqtt.MessageCache;
using BanZuiCloudControlAgent.Core.Mqtt.Models;
using BanZuiCloudControlAgent.Core.Mqtt.Sender;
using BanZuiCloudControlAgent.Core.QQ;
using BanZuiCloudControlAgent.Core.Startup;
using BanZuiCloudControlAgent.Extensions.QQ;
using BanZuiCloudControlAgent.Utils.Common;
using BanZuiCloudControlAgent.Utils.Exceptions;
using BanZuiCloudControlAgent.Utils.Logging;

namespace BanZuiCloudControlAgent.Utils.Common
{
    /// <summary>
    /// Autofac依赖注入容器配置类
    /// </summary>
    public static class ContainerConfig
    {
        private static IContainer _container;
        private static bool _isConfiguring = false;

        /// <summary>
        /// 初始化依赖注入容器
        /// </summary>
        public static void Initialize()
        {
            if (_container == null && !_isConfiguring)
            {
                Configure();
            }
        }

        /// <summary>
        /// 配置并构建依赖注入容器
        /// </summary>
        /// <returns>配置好的容器实例</returns>
        public static IContainer Configure()
        {
            if (_container != null)
            {
                return _container;
            }

            // 防止递归调用
            if (_isConfiguring)
            {
                throw new InvalidOperationException("容器正在配置中，检测到递归调用");
            }

            try
            {
                _isConfiguring = true;

                var builder = new ContainerBuilder();

                // 注册配置服务 - 使用已存在的单例实例
                builder.RegisterInstance(ConfigurationService.Instance).AsSelf().SingleInstance();
                builder.RegisterType<AppSettings>().AsSelf().SingleInstance();
                
                // 注册日志服务
                builder.Register(c => LogManager.GetLogger("Default")).Named<Logger>("DefaultLogger");
                builder.Register(c => LogManager.GetLogger(c.ResolveOptional<string>() ?? "Default")).As<Logger>();

                // 注册异常处理器
                builder.RegisterType<ExceptionHandler>().AsSelf();

                // 注册MQTT服务
                builder.RegisterType<MqttClientOptions>().AsSelf().SingleInstance();
                builder.RegisterType<MqttClientManager>().AsSelf().SingleInstance();
                builder.RegisterType<MqttMessageSender>().AsSelf().SingleInstance();
                builder.RegisterType<MqttMessageHandler>().AsSelf().SingleInstance();
                builder.RegisterType<MqttMessageListener>().AsSelf().SingleInstance();
                builder.RegisterType<MqttMessageCache>().AsSelf().SingleInstance();
                builder.RegisterType<MqttService>().AsSelf().SingleInstance();

                // 注册启动管理器
                builder.RegisterType<StartupManager>().AsSelf().SingleInstance();

                // 注册QQ相关服务
                builder.RegisterType<QQManager>().AsSelf().SingleInstance();
                
                // 注册QQ自动化服务
                builder.RegisterType<QQAutomation>().AsSelf().SingleInstance();

                // 注册工具类
                builder.RegisterType<CacheManager>().AsSelf().SingleInstance();

                _container = builder.Build();
                return _container;
            }
            finally
            {
                _isConfiguring = false;
            }
        }

        /// <summary>
        /// 获取全局容器实例
        /// </summary>
        public static IContainer Container 
        { 
            get 
            {
                if (_container == null)
                {
                    // 如果已经在配置过程中，直接返回null，避免递归
                    if (_isConfiguring)
                    {
                        throw new InvalidOperationException("容器正在配置中，无法访问Container属性");
                    }
                    Configure();
                }
                return _container;
            }
        }

        /// <summary>
        /// 从容器中解析服务
        /// </summary>
        /// <typeparam name="T">服务类型</typeparam>
        /// <returns>服务实例</returns>
        public static T Resolve<T>() where T : class
        {
            return Container.Resolve<T>();
        }
    }
} 